/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* build(vector<int>& preorder, vector<int>& inorder,int& prei,int left,int right){
        if(left>right) return nullptr;

        TreeNode* root = new TreeNode(preorder[prei]);
        int rooti = left;
        while(rooti<=right)
        {
            if(preorder[prei]==inorder[rooti]) break;
            else rooti++;
        }
        prei++;
        // [left,rooti-1] root [rooti+1,right]
        root->left = build(preorder,inorder,prei,left,rooti-1);
        root->right = build(preorder,inorder,prei,rooti+1,right);
        
        return root;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int prei = 0;
        return build(preorder,inorder,prei,0,inorder.size()-1);
    }
};